package org.jeecg.common.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DictUtil {

	@Autowired
	private CommonAPI commonAPI;

	public JSONObject parseObjectDict(Object entity){
		JSONObject item =  (JSONObject) JSONObject.toJSON(entity);
		for (Field field : oConvertUtils.getAllFields(entity)) {

			if (field.getAnnotation(Dict.class) != null) {
				String code = field.getAnnotation(Dict.class).dicCode();
				String text = field.getAnnotation(Dict.class).dicText();
				String table = field.getAnnotation(Dict.class).dictTable();
				String key = String.valueOf(item.get(field.getName()));

				//翻译字典值对应的txt
				String textValue = translateDictValue(code, text, table, key);

				log.debug(" 字典Val : " + textValue);
				log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + "： " + textValue);
				item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
			}
			//date类型默认转换string格式化日期
			if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
				SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
			}
		}
		return item;
	}

	public List<?> parseArrayListDict(List<?> objlist){
		if (objlist instanceof ArrayList) {
			List<JSONObject> items = new ArrayList<>();
			ArrayList arrayList = (ArrayList) objlist;
			for (Object record : arrayList) {
				ObjectMapper mapper = new ObjectMapper();
				String json="{}";
				try {
					//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
					json = mapper.writeValueAsString(record);
				} catch (JsonProcessingException e) {
					log.error("json解析失败"+e.getMessage(),e);
				}
				JSONObject item = JSONObject.parseObject(json);
				//update-begin--Author:scott -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
				//for (Field field : record.getClass().getDeclaredFields()) {
				for (Field field : oConvertUtils.getAllFields(record)) {
					//update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
					if (field.getAnnotation(Dict.class) != null) {
						String code = field.getAnnotation(Dict.class).dicCode();
						String text = field.getAnnotation(Dict.class).dicText();
						String table = field.getAnnotation(Dict.class).dictTable();
						String key = String.valueOf(item.get(field.getName()));

						//翻译字典值对应的txt
						String textValue = translateDictValue(code, text, table, key);

						log.debug(" 字典Val : "+ textValue);
						log.debug(" __翻译字典字段__ "+field.getName() + CommonConstant.DICT_TEXT_SUFFIX+"： "+ textValue);
						item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
					}
					//date类型默认转换string格式化日期
					if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
						SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
					}
				}
				items.add(item);
			}
			return items;
		}
		return objlist;
	}
	/**
	 *  翻译字典文本
	 * @param code
	 * @param text
	 * @param table
	 * @param key
	 * @return
	 */
	private String translateDictValue(String code, String text, String table, String key) {
		if(oConvertUtils.isEmpty(key)) {
			return null;
		}
		StringBuffer textValue=new StringBuffer();
		String[] keys = key.split(",");
		for (String k : keys) {
			String tmpValue = null;
			log.debug(" 字典 key : "+ k);
			if (k.trim().length() == 0) {
				continue; //跳过循环
			}
			if (!StringUtils.isEmpty(table)){
				log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
				tmpValue= commonAPI.translateDictFromTable(table,text,code,k.trim());
			}else {
				tmpValue = commonAPI.translateDict(code, k.trim());
			}
			if (tmpValue != null) {
				if (!"".equals(textValue.toString())) {
					textValue.append(",");
				}
				textValue.append(tmpValue);
			}

		}
		return textValue.toString();
	}
}
